package Init;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.sun.org.glassfish.external.statistics.annotations.Reset;

import Log.LU;

public class InitDatabase extends HttpServlet {

	/**
	 * Constructor of the object.
	 */
	public InitDatabase() {
		super();
	}

	/**
	 * Destruction of the servlet. <br>
	 */
	public void destroy() {
		super.destroy(); // Just puts "destroy" string in log
		// Put your code here
	}

	/**
	 * The doPost method of the servlet. <br>
	 *
	 * This method is called when a form has its tag value method equals to post.
	 * 
	 * @param request the request send by the client to the server
	 * @param response the response send by the server to the client
	 * @throws ServletException if an error occurred
	 * @throws IOException if an error occurred
	 */
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		response.setContentType("text/html");
		PrintWriter out = response.getWriter();
		out.println("请勿访问！ Don't explorer this page!");
		out.flush();
		out.close();
	}

	/**
	 * Initialization of the servlet. <br>
	 *
	 * @throws ServletException if an error occurs
	 */
	public void init() throws ServletException {
		// Put your code here
		LU.l("InitDatabase Init Progressing! BraeThing Project : Server Will Be Ready To Use Mysql Database On Localhost!");
		String dburl=getInitParameter("dburl");
		String username=getInitParameter("username");
		String password=getInitParameter("password");
		ServletContext application=getServletContext();
		application.setAttribute("dburl", dburl);
		application.setAttribute("username", username);
		application.setAttribute("password", password);
		try {
			Class.forName("com.mysql.jdbc.Driver");
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			LU.e("InitDatabase Init Failure! BraeThing Cannot Find Database System In JDBC Symbol. Your Server In TOMCAT Will Be KILLED!");
			System.exit(1);
		}
		try {
			Connection con=DriverManager.getConnection(dburl, username, password);
			application.setAttribute("con", con);
			LU.l("InitDatabase Susscefully To Get Connection With Mysql Database System!");
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			LU.e("InitDatabase Init Failure! BraeThing Cannot Connect To Mysql Database System In JDBC Symbol. Your Server In TOMCAT Will Be KILLED!");
			System.exit(1);
		}
		LU.l("InitDatabase Init Succes! BreaThing Project : Server System Had Ready To Get/Post Request!");
	}
}
